<template>
    <a-upload
        name="avatar"
        listType="picture-card"
        class="avatar-uploader"
        :showUploadList="false"
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        :beforeUpload="beforeUpload"
        @change="handleChange"
    >
        <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
        <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">图片</div>
        </div>
    </a-upload>
</template>
<script>
    import {getBase64} from "@/utils/ImageBase64";
  export default {
    data() {
      return {
        loading: false,
        imageUrl: '',
      };
    },
    methods: {
      handleChange(info) {
        var than = this
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl => {
            this.imageUrl = imageUrl;
            this.loading = false;
            than.http('post','upload/upload',{image:imageUrl}).then(res=>{
                this.$emit('uploadImg',res)
            })
          });
        }
      },
      beforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!');
        }
        return isLt2M;
      },
    },
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /deep/.ant-upload.ant-upload-select-picture-card{
      width: 150px;
      height: 150px;
    img{
        width: 150px;
        height: 150px;
    }
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>